import axios from 'axios'
import qs from 'qs'
import store from '~vuex/store'
import config from '~src/config'
import util from '~src/lib/util'

axios.interceptors.request.use(config => {
  return config
}, error => {
  console.log(redirect)
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  return response
}, error => {
  store.dispatch('TOAST_SHOW', {content: error.toString(), msg: true})
  return Promise.reject(error)
})

function checkStatus (response) {
  if (response.status === 200 || response.status === 304) {
    return response
  }
  return {
    data: {
      code: -400,
      message: response.statusText
    }
  }
}

function checkCode (res) {
  if (res.data.code === -500) {
    return
  } else if (res.data.code === '404') {
    store.dispatch('TOAST_HIDE')
  } else if (res.data.code === '401') {
    store.dispatch('TOAST_SHOW', {content: '参数有问题', msg: true})
    return
  } else if (res.data.code === '200') {
    store.dispatch('TOAST_HIDE')
  } else if (res.data.code !== '200' && res.data.errMsg) {
    store.dispatch('TOAST_SHOW', {content: res.data.errMsg, msg: true})
  }
  return res
}
// let _token = (util.localItem.get('token')?'/token/':'') + util.localItem.get('token') // 获取token
let _token = '/token/40ST5V69JC2D7QPAYIW38MXHFRNZLOGUB1KE'
export default {
  post (url, data) {
    return axios({
      method: 'post',
      url: config._URL_API_ + url + _token,
      data: qs.stringify(data),
      timeout: config.timeout,
      onUploadProgress: function (progressEvent) {
        store.dispatch('TOAST_SHOW', {autoClose: false, toast: true, loading: true})
      },
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }).then(checkStatus).then(checkCode)
  },
  get (url, params) {
    return axios({
      method: 'get',
      url: config._URL_API_ + url + _token ,
      withCredentials: true,
      params,
      timeout: config.timeout,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
      }
    }).then(checkStatus).then(checkCode)
  }
}
